package com.dragonwu.model;

import com.alibaba.fastjson.annotation.JSONField;
import com.dragonwu.model.entity.SysUser;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author DragonWu
 * @since 2022-10-06 20:29
 **/
@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {

    private SysUser sysUser;

    //用户角色权限
    private List<String> jurisdiction;

    //将不会被序列化到redis里
    @JSONField(serialize = false)
    private List<SimpleGrantedAuthority> authorities;

    public LoginUser(SysUser sysUser, List<String> jurisdiction) {
        this.sysUser = sysUser;
        this.jurisdiction = jurisdiction;
    }

    public String getJurisdictionToString() {
        return StringUtils.join(jurisdiction, ',');
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //把jurisdiction里的权限信息字符串封装成SimpleGrantedAuthority对象
        if (!Objects.isNull(authorities)) {
            return authorities;
        }
        authorities = jurisdiction.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        return authorities;
    }

    @Override
    public String getPassword() {
        return sysUser.getPassword();
    }

    @Override
    public String getUsername() {
        return sysUser.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
